package com.zcgame.customview.imageview

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatImageView
import com.zcgame.base.utils.DensityUtil
import com.zcgame.customview.R

/**
 *@author:huangLJ
 *@date:2021/6/28 18:57
 */
class RoundRectImageView @JvmOverloads constructor(context:Context,
        val attributeSet: AttributeSet? = null,
        val defs:Int = 0)
    :AppCompatImageView(context,attributeSet,defs) {


    private var path = Path()
    private var rect:RectF? = null
    private var rids = FloatArray(8)
    private var radius = 0F
    private var paintFlagsDrawFilter:PaintFlagsDrawFilter? = null
    init {
        val a =
            context.obtainStyledAttributes(attributeSet!!, R.styleable.RoundRectImageView)
        radius = a.getDimension(R.styleable.RoundRectImageView_radius, 0F)
        rids[0] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_left_top, 0F)).toFloat()
        rids[1] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_left_top, 0F)).toFloat()
        rids[2] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_right_top,0F)).toFloat()
        rids[3] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_right_top,0F)).toFloat()
        rids[4] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_left_bottom,0F)).toFloat()
        rids[5] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_left_bottom,0F)).toFloat()
        rids[6] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_left_bottom,0F)).toFloat()
        rids[7] =
            DensityUtil.dip2px(a.getDimension(R.styleable.RoundRectImageView_radius_left_bottom,0F)).toFloat()
        a.recycle()
        if(radius!=0f){
            rids.forEachIndexed {index, _ ->
                rids[index] = radius
            }
        }
        paintFlagsDrawFilter = PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
    }
    override fun onDraw(canvas: Canvas?) {
        path.reset()

        if(rect!=null){
            path.addRoundRect(rect!!,rids,Path.Direction.CW)
        }
        canvas?.drawFilter = paintFlagsDrawFilter
        canvas?.save()
        canvas?.clipPath(path)
        super.onDraw(canvas)
        canvas?.restore()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        Log.d("HuangLJ","width--> $w")
        Log.d("HuangLJ","height--> $h")
        rect = RectF(0F,0F, w.toFloat(), h.toFloat())
    }
}
